<template>
  <div class="auth-form">
    <h2 class="form-title">欢迎回来</h2>
    <div class="input-group">
      <input 
        v-model="username" 
        type="text" 
        placeholder="用户名" 
        @keyup.enter="handleLogin"
      />
    </div>
    <div class="input-group">
      <input 
        v-model="password" 
        type="password" 
        placeholder="密码" 
        @keyup.enter="handleLogin"
      />
    </div>
    <button class="submit-btn" @click="handleLogin" :disabled="loading">
      <template v-if="!loading">登录</template>
      <LoadingIndicator v-else />
    </button>
    
    <!-- 错误信息 -->
    <div v-if="error" class="status-message error">
      <i class="status-icon">✕</i>
      <span>{{ error }}</span>
    </div>

    <button class="switch-form-btn" @click="$emit('switch-form')">
      没有账号？点击注册
    </button>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { useUserStore } from '@/stores/user'
import LoadingIndicator from './LoadingIndicator.vue'

const username = ref('')
const password = ref('')
const loading = ref(false)
const error = ref('')

const userStore = useUserStore()

const props = defineProps({
  modalRef: {
    type: Object,
    required: true
  }
})

const resetForm = () => {
  username.value = ''
  password.value = ''
  error.value = ''
  loading.value = false
}

const handleLogin = async () => {
  if (!username.value || !password.value) {
    error.value = '请填写用户名和密码'
    return
  }

  loading.value = true
  error.value = ''
  
  try {
    console.log('开始登录...')
    const result = await userStore.loginUser(username.value, password.value)
    console.log('登录返回结果:', result)
    
    if (result.success && result.data) {
      console.log('登录成功，用户数据:', result.data)
      console.log('登录后的状态:', {
        isLoggedIn: userStore.isLoggedIn,
        token: userStore.token,
        username: userStore.username
      })
      props.modalRef.handleAuthSuccess()
    } else {
      error.value = result.message
      console.log('登录失败:', result.message)
    }
  } catch (err) {
    console.error('登录发生错误:', err)
    error.value = '登录失败，请稍后重试'
  } finally {
    loading.value = false
  }
}

defineEmits(['switch-form'])
defineExpose({ resetForm })
</script>

<style scoped lang="scss">
@import '@/styles/_auth-forms.scss';

.status-message {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 12px;
  border-radius: 8px;
  font-size: 14px;
  
  &.error {
    background: rgba(#ff4444, 0.1);
    color: #ff4444;
    border: 1px solid rgba(#ff4444, 0.2);
  }

  .status-icon {
    font-size: 16px;
    font-style: normal;
  }
}
</style>
